//
//  AppDelegate.swift
//  WeatherTools
//
//  Created by 刘飞龙 on 2020/8/30.
//  Copyright © 2020 finals. All rights reserved.
//

import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, WeatherCallback {
    func onSuccess(weather: String,url:URL) {
        self.statusItem.button?.image = NSImage(byReferencing: url)
        self.statusItem.button?.imagePosition = NSControl.ImagePosition.imageLeft
        self.statusItem.button?.title = weather
    }
    
    func onFailed(error: String) {
         self.statusItem.button?.title = "更新失败"
    }
    

    var window: NSWindow!
    
    @IBOutlet weak var menu: NSMenu!

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()

        // Create the window and set the content view. 
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
        showMenuBar()
        getWeather(callback:self)
    }
    
    func showMenuBar(){
        if let button:NSStatusBarButton = statusItem.button {
            button.title = "正在加载"
        }
        statusItem.menu = menu
    }
    
    func getWeather(callback:WeatherCallback){
        let service = WeatherService()
        //郑州
        var cityCode:NSString = "101180101"
        //深圳
        cityCode = "101280601"
        //沈阳
        //cityCode = "101070101"
        service.getWeather(cityCode: cityCode, callback: callback)
    }
    
    @IBAction func quitClick(_sender:Any){
        NSApplication.shared.terminate(self)
    }
    
    @IBAction func updateClick(_sender:Any){
        let location:LocationService = LocationService();
        location.updateLocation()
        getWeather(callback:self)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


}

